/**
 * LeetCode65：有效数字
 * 验证给定的字符串是否可以解释为十进制数字
 */

/**
 *
 * @param {String} s
 * @return {boolean}
 */
var isNumber = function (s){
    //构建一张图，表示字符串拼接的状态
    //字符串拼接时，按照拼接的字符，沿着图前进，最终达到状态3/5/6，表示字符串有效
    //该图的示意图见/note/JavaScript/图.md
    const graph = {
        0:{'blank':0,'sign':1,'.':2,'digit':6},
        1:{'digit':6,'.':2},
        3:{'digit':3,'e':4},
        4:{'digit':5,'sign':7},
        5:{'digit':5},
        6:{'digit':6,'.':3,'e':4},
        7:{'digit':5}
    };

    let state = 0;
    //遍历字符串的每个字符
    //将字符转换为规则图中每条边定义的字符
    for (c of s.trim()) {
        if (c >= '0' && c <= '9'){
            c = 'digit';
        }else if (c === ' '){
            c = 'blank';
        }else if (c === '+' || c === '-'){
            c = 'sign';
        }
        state = graph[state][c];
        if (state === undefined){
            return false;
        }
    }
    if (state == 3 || state == 5 || state == 6){
        return true;
    }else {
        return false;
    }
};

//时间复杂度：O(n)
//空间复杂度：O(1)